package Words.Test;

import Words.Mapper.WordMapper;
import Words.Pojo.Word;
import Words.Utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.jupiter.api.Test;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static Words.Utils.MybatisUtils.*;
import static java.lang.Thread.sleep;

public class Tests {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    WordMapper wordMapper = sqlSession.getMapper(WordMapper.class);
    /**
     *
     * 单词爬虫
     *
     * */
    @Test
    public void CrawlerWords() throws Exception {
        for (int i=0;i<=176;i++){
            Document parse = Jsoup.parse(new URL("https://www.quword.com/study/TEM4/"+i), 6000);
            sleep(5000);
            Elements wordMainList = parse.getElementsByClass("swiper-slide");
            for (Element element:wordMainList){
                Elements caption = element.getElementsByClass("caption");
                for (Element element1 :caption){
                    System.out.println("-----------------------------------------------------------------");
                    String p = element1.select("p").text();
                    String h3 = element.select("h3").text();
                    Word word=new Word(h3,p);
                    wordMapper.insert(word);
                }
            }
            System.out.println(i);
        }
    }
    @Test
    public void textToSpeechTest(){
        String text = "(((((((((((((((((((((((((((((((((((((((((((我是傻逼)))))))))))))))))))))))))))))))))))))))))))";
        Word rearch = wordMapper.GetWordByKey("researh");
//        ForeInformation foreInformation=new ForeInformation(rearch.getWID(),rearch.getInformation(),returntextToSpeechbyte(rearch.getExplain()),null);
        byte[] audioData = returntextToSpeechbyte(text);
        System.out.println(audioData);
        // 将音频数据保存成.wav文件
        try {
            AudioFormat format = new AudioFormat(22050, 16, 1, true, false);
            AudioInputStream audioInputStream = new AudioInputStream(new ByteArrayInputStream(audioData), format, audioData.length);
            AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, new File("F:\\Desktop\\output.mp3"));
            audioInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void Insert(){
        String fileName = "src\\main\\java\\Words\\text\\Vocabulary.txt";
        List<List<String>> data = processFile(fileName);
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        WordMapper wordMapper = sqlSession.getMapper(WordMapper.class);
        int i=0;
        for (List<String> line : data) {
            System.out.println(i);
            Word word=new Word(line.get(0),line.get(1));
            wordMapper.insert(word);
            i++;
        }
    }

    @Test
    public void QuaryNullObject(){
        List<Integer> integers = wordMapper.GetNullObject();
        System.out.println(integers.size());
        for (int i:integers){
            try {
                Connection.Response resultImageResponse = Jsoup.connect("https://dict.youdao.com/dictvoice?audio="+wordMapper.GetWordById(i).getWords()+"&type=2").ignoreContentType(true).execute();
                InputStream in = resultImageResponse.bodyStream();
                byte[] buffer = new byte[4096];
                byte[] bytes = in.readAllBytes();
                int n;
                wordMapper.updat(wordMapper.GetWordById(i).getWords(),bytes);
                in.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }


    }



    /**
     * 从有道词典爬取解释
     *
     *
     * */
    @Test
    public void  ExplainCrawler () throws Exception {
        List<Word> words = wordMapper.getWords();
        List<List<byte[]>>information=new ArrayList<>();
        int i=0;
        for (Word word:words){
            Document parse = Jsoup.parse(new URL("https://www.youdao.com/result?word=" + word.getWords() + "&lang=en"), 6000);
            Elements elementsByClass = parse.getElementsByClass("sen-eng");
            List<byte[]>information1=new ArrayList<>();
            for (Element element:elementsByClass){
                information1.add(element.text().getBytes());
            }
            byte[] bytes = convertListToByteArray(information1);
            wordMapper.updat0(word.getWords(),bytes);
        }
    }



    @Test
    public  void ShowInformation(){
        Word word = wordMapper.GetWordById(1);
        String str = new String(word.getInformation(), StandardCharsets.UTF_8);
        System.out.println(str);
    }
    public void insertInformation(String key){

        byte[]ByteInformation=new byte[10000];
        String information="";
        try {
            Document parse = Jsoup.parse(new URL("https://www.quword.com/w/" + key ), 6000);
            Element elementById = parse.getElementById("yd-liju");
            Elements dl = elementById.getElementsByTag("dl");
            for (Element element:dl){
                Elements dt = element.select("dt");
                Elements dd = element.select("dd");
                information=information+dt.text()+".......";
                ByteInformation=information.getBytes(StandardCharsets.UTF_8);
                wordMapper.updat0(key,ByteInformation);
            }
        } catch (Exception e) {
            ByteInformation="没有例句".getBytes(StandardCharsets.UTF_8);
            wordMapper.updat0(key,ByteInformation);

        }

    }
    public void InsertWordAndExplain(String key) throws Exception {
        Document parse = Jsoup.parse(new URL("https://www.quword.com/w/" + key ), 6000);
        Element elementById = parse.getElementById("yd-word-meaning");
        Elements li = elementById.getElementsByTag("li");
        System.out.println("li结果"+li.text());
        if (!li.text().equals("")){
            Word word = new Word(key, li.text());
            wordMapper.insert(word);

            Document parse1 = Jsoup.parse(new URL("https://www.youdao.com/result?word=" + word.getWords() + "&lang=en"), 6000);
            Elements elementsByClass = parse1.getElementsByClass("sen-eng");
            List<byte[]>information1=new ArrayList<>();
            for (Element element:elementsByClass){
                information1.add((element.text()+".......").getBytes());
            }
            byte[] bytes = convertListToByteArray(information1);

            wordMapper.updat0(word.getWords(),bytes);
            Connection.Response resultImageResponse = Jsoup.connect("https://dict.youdao.com/dictvoice?audio="+word.getWords()+"&type=2").ignoreContentType(true).execute();
            InputStream in = resultImageResponse.bodyStream();
            byte[] buffer = new byte[4096];
            byte[] bytes1 = in.readAllBytes();
            int n;
            wordMapper.updat(word.getWords(),bytes1);
            in.close();
        }
    }


    /**
     *
     * 单词爬虫
     *
     *
     *
     *
     *
     * */
    @Test
    public void EST() throws Exception {
        for (int i=0;i<=19;i++){
            Document parse = Jsoup.parse(new URL("https://www.quword.com/study/learn.php?level=6&page="+i), 6000);
            sleep(5000);                   ///https://www.quword.com/study/learn.php?level=6&page=0
            Elements wordMainList = parse.getElementsByClass("swiper-slide");
            for (Element element:wordMainList){
                Elements caption = element.getElementsByClass("caption");
                for (Element element1 :caption){
                    System.out.println("-----------------------------------------------------------------");
                    String h3 = element.select("h3").text();
                    String p = element1.select("p").text();
                    Word word1 = wordMapper.GetWordByKey(h3);
                    if (word1==null){
                        Word word=new Word(h3,p);
                        wordMapper.insert(word);
                        System.out.println("插入"+word.getWords());
                    }


//


                }
            }
            System.out.println("第几"+i+"页");
        }

    }
    /**
     *
     *
     * 单词读音爬虫
     *
     *
     * */
    @Test
    public void Mp3Crawler() throws Exception {
        int i1=0;
        for (int i=14201;i<=14202;i++){
            Word word = wordMapper.GetWordById(i);
            try {
                Connection.Response resultImageResponse = Jsoup.connect("https://dict.youdao.com/dictvoice?audio="+word.getWords()+"&type=2").ignoreContentType(true).execute();
                InputStream in = resultImageResponse.bodyStream();
                byte[] buffer = new byte[4096];
                byte[] bytes = in.readAllBytes();
                int n;
                wordMapper.updat(word.getWords(),bytes);
                in.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 单词例句爬虫
     *
     *
     * */
    @Test
    public void  InformationCrawler() throws Exception {
        for (int i=10035;i<=14201;i++){
            Word word = wordMapper.GetWordById(i);
            System.out.println("-----------------------------" + word.getWords() + "-----------------------------");

            byte[]ByteInformation=new byte[10000];
            String information="";
            try {
                Document parse = Jsoup.parse(new URL("https://www.quword.com/w/" + word.getWords() ), 6000);
                Element elementById = parse.getElementById("yd-liju");
                Elements dl = elementById.getElementsByTag("dl");
                for (Element element:dl){
                    Elements dt = element.select("dt");
                    Elements dd = element.select("dd");
                    information=information+dt.text()+".......";
                    ByteInformation=information.getBytes(StandardCharsets.UTF_8);
                    wordMapper.updat0(word.getWords(),ByteInformation);
                }
            } catch (Exception e) {
                ByteInformation="没有例句".getBytes(StandardCharsets.UTF_8);
                wordMapper.updat0(word.getWords(),ByteInformation);

            }

            System.out.println(Arrays.toString(ByteInformation));

        }
    }
    public static void main(String[] args) throws Exception {
//        String s = "你好";
//        textToSpeech(s);
//        Tests tests=new Tests();
//        tests.InsertWordAndExplain(" asynchronous");


    }
    @Test
    public void GetWordBiganOfKey(){
        List<Word> com = wordMapper.GetWordBiganOfKey("g",14000);
        for (Word word:com){
            System.out.println(word.getWords());
        }

    }
}
